import 'dart:io';

import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart';

import 'permission_check_dialog.dart';

class PermissionHelper {
  static final PermissionHelper _permissionHelper =
      PermissionHelper._internal();

  factory PermissionHelper.instance() {
    return _permissionHelper;
  }

  PermissionHelper._internal();

  /// 检查并请求权限，如果没有请求的相关权限组的权限会向用户直接申请，并处理申请拒绝的逻辑
  /// iOS仅请求一次权限，Android如下：
  /// 1、初次检测某权限  弹出解释弹窗，n秒自动消失（可选,默认一直展示） 拒绝、允许后自动消息
  /// 2、权限被拒 弹出打开设置弹窗（可选,在没有权限不影响业务的地方建议关闭 如 定位、通知）

  ///返回值 如已有权限返回true, 否则 false
  static Future<bool> checkAndRequestPermission(
    BuildContext context,
    Permission permission, {
    bool showTipsDialog = true,
    String? tipsTitle,
    String? tipsContent,
    bool showOpenSetting = true,
    String? openSettingTips,
  }) async {
    bool isGranted =
        await PermissionHelper.instance().checkPermissionsIsGranted(permission);

    if (isGranted) {
      return isGranted; //已获得授权
    }

    if (Platform.isAndroid && showTipsDialog && context.mounted) {
      Navigator.push(
        context,
        _PopRoute(
          child: PermissionCheckDialog(
            permissions: [permission],
            title: tipsTitle,
            tips: tipsContent,
          ),
        ),
      );
    }

    //1、直接申请
    isGranted = await PermissionHelper.instance().requestPermission(permission);
    if (PermissionCheckDialog.isShowingDialog) {
      await Future.delayed(const Duration(milliseconds: 300));
      if (context.mounted) {
        await PermissionCheckDialog.dismissPermissionDialog(context);
      }
    }

    if (isGranted) {
      return true;
    }

    if (Platform.isAndroid && showOpenSetting) {
      await Future.delayed(const Duration(milliseconds: 20));
      if (context.mounted) {
        var result = await Navigator.push(
          context,
          _PopRoute(
            child: OpenSettingDialog(
                permission: permission, tips: openSettingTips),
          ),
        );
        if (result) {
          return true;
        }
      }
    }
    return false;
  }

  ///检查权限是否都被授予
  Future<bool> checkPermissionsIsGranted(Permission permission) async {
    PermissionStatus status = await permission.status;
    if (Platform.isIOS) {
      return status.isGranted || status.isLimited;
    }
    return status.isGranted;
  }

  ///请求权限
  Future<bool> requestPermission(Permission permission) async {
    final status = await permission.request();
    if (Platform.isIOS) {
      return status.isGranted || status.isLimited;
    }

    return status.isGranted;
  }

  ///检查权限是否都被授予
  Future<bool> checkPermissionsGranted(List<Permission> permissions) async {
    for (var element in permissions) {
      var result = false;
      if (Platform.isIOS) {
        result =
            await element.status.isGranted || await element.status.isLimited;
      } else {
        result = await element.status.isGranted ? true : false;
      }
      if (result != true) {
        return false;
      }
    }
    return true;
  }

  ///检测权限是否可以动态申请
  Future<bool> shouldShowRequestPermissionRationale(
      Permission permission) async {
    bool shouldShowRequestPermissionRationale =
        await permission.shouldShowRequestRationale;
    if (!shouldShowRequestPermissionRationale) {
      shouldShowRequestPermissionRationale =
          shouldShowRequestPermissionRationale =
              await permission.status.isGranted;
    }
    return shouldShowRequestPermissionRationale;
  }
}

class _PopRoute<int> extends PopupRoute {
  final Duration _duration = const Duration(milliseconds: 30);
  Widget child;

  _PopRoute({required this.child});

  @override
  bool get barrierDismissible => true;

  @override
  get barrierLabel => null;

  @override
  Widget buildPage(BuildContext context, Animation<double> animation,
      Animation<double> secondaryAnimation) {
    return child;
  }

  @override
  Duration get transitionDuration => _duration;

  @override
  Color? get barrierColor => null;
}
